/* Copyright © 2023 - 2024 Coremail论客
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { Connection, NetworkState } from "./network";
import { getLogger } from "../utils/log";
import { ErrorCode, IBufferCreator, CMError } from "../api";
import { memBufferCreator } from '../utils/file_stream';
import { delay, TaskQueue } from '../utils/common';

const logger = getLogger("protocol");

export type RawResult = {
  ok: boolean;
  data: string[];
};

export interface ICommand<T> {
  do(conn: Connection): Promise<T>;
}

export class ProtocolBase<T> {
  conn: Connection;
  nextPromise?: Promise<unknown>;
  _hasError: boolean = false;
  _idle: boolean = true;
  _bufferCreator: IBufferCreator = memBufferCreator;
  _taskQueue: TaskQueue = new TaskQueue();

  constructor(host: string, port: number, isSSL: boolean, ca: string[] = []) {
    this.conn = new Connection(host, port, isSSL, ca);
  }

  async connect() : Promise<void> {
    logger.debug('connect')
    await this.conn.connect();
    await this.onConnected();
  }

  setBufferCreator(creator: IBufferCreator): void {
    this._bufferCreator = creator;
  }

  async onConnected(): Promise<void> {
    logger.debug("onConnected");
  }

  hasError(): boolean {
    return this._hasError;
  }

  isReady(): boolean {
    return this.conn.state == NetworkState.CONNECTED;
  }

  /*
   * 执行一个协议命令。由于协议都必须一个命令执行完再进行下一个，需要排队
   */
  async doCommand(command: ICommand<T>): Promise<T> {
    logger.trace("do command", command, this.conn.state);
    if (!this.isReady()) {
      const text = "do command when connection failed";
      logger.error("doCommand no connection", command);
      return Promise.reject(new CMError(text));
    }

    const task = await this._taskQueue.wait();
    try {
      const r = await command.do(this.conn);
      return r;
    } catch(e: unknown) {
      logger.error("execute command failed", e);
      this.conn.resetData();
      if (e instanceof CMError) {
        if (e.code == ErrorCode.PROTOCOL_TIMEOUT) {
          this._hasError = true;
        }
        return Promise.reject(e);
      } else {
        const error = new CMError("command failed", ErrorCode.PROTOCOL_EXECUTE_COMMAND_FAILED, e);
        return Promise.reject(error);
      }
    }
    finally {
      task.finish();
    }
  }

  stop(): void {
    this.conn.close();
  }
}
